﻿#include "TextInSceneReadLineFunction.h"

#include <QTextDocument>
#include <QTextBlock>

#include "TextInSceneWidget.h"

class TextInSceneReadLineFunction::TextInSceneReadLineFunctionPrivate :QObject
{
public:
	int in_params[16];
	int out_params[1];
	int in_count;
	int out_count;
public:
	TextInSceneReadLineFunctionPrivate(QObject*parent) :QObject(parent)
	{
		in_count = 2;
		out_count = 1;

		in_params[0] = FPT_PTR;
		in_params[1] = FPT_NUMBER;
		out_params[0] = FPT_STRING;
	}

};

TextInSceneReadLineFunction::TextInSceneReadLineFunction(QObject *parent)
	: QObject(parent),private_ptr(new TextInSceneReadLineFunctionPrivate(this))
{
}

TextInSceneReadLineFunction::~TextInSceneReadLineFunction()
{
}

static int TextInSceneReadLineFunction_FUNCTION(struct variant_s *in, int in_count, struct variant_s *out, void*tag)
{
	if (2 != in_count)
		return ERR_PARAM_NOT_MATCH;

	// 判断第一个参数
	if (VALUETYPE_VOID_PTR != in[0].type)
		return ERR_DATATYPE_NOT_MATCH;
	if (nullptr == in[0].u.ptr)
		return ERR_DATATYPE_NOT_MATCH;

	// 判断第二个参数
	if (VALUETYPE_DOUBLE != in[1].type)
		return ERR_DATATYPE_NOT_MATCH;

	int row = (int)in[1].u.d;


	QTextDocument*doc = nullptr;
	AstScene*as = nullptr;
	TextInSceneWidget*ptr = nullptr;
	try {
		as = (AstScene*)in[0].u.ptr;
		ptr = dynamic_cast<TextInSceneWidget*>(as->widget());
		doc = ptr->textDocument();
	}
	catch (...) {
		doc = nullptr;
	}

	QString line = doc->findBlockByLineNumber(row).text();

	out->type = VALUETYPE_STRING;
	out->u.ptr = _strdup(line.toUtf8().data());

	return 0;
}

AstFunction* TextInSceneReadLineFunction::operator()()
{
	return dynamic_cast<AstFunction*>(this);
}

QString TextInSceneReadLineFunction::name()
{
	return "TextInSceneReadLine";
}
int* TextInSceneReadLineFunction::outputTypes()
{
	return private_ptr->out_params;
}
int TextInSceneReadLineFunction::outputCount()
{
	return private_ptr->out_count;
}
int* TextInSceneReadLineFunction::inputTypes()
{
	return private_ptr->in_params;
}
int TextInSceneReadLineFunction::inputCount()
{
	return private_ptr->in_count;
}
void* TextInSceneReadLineFunction::function()
{
	return TextInSceneReadLineFunction_FUNCTION;
}
